<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1"><title>JavaScript 常见算法 | Cyan</title><meta name="author" content="Cyan,843348394@qq.com"><meta name="copyright" content="Cyan"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="前言看这篇文章之前，我们不妨自问一下，我们为什么要去学习算法？这个对我们有什么好处？  学习算法可以开拓我们的思维，让我们的逻辑更加严谨 学习算法是成为一名优秀的开发者的途径之一 可以高质、高效地完成我们业务上的需求    排序算法冒泡排序 依次比较相邻的两个元素，根据大小互换位置，保证每一次比较大的数都在最后 重复n+1次，就可完成排序    1234567891011121314&#x2F;&#x2F; 时间复杂"><meta property="og:type" content="article"><meta property="og:title" content="JavaScript 常见算法"><meta property="og:url" content="https://xmwpro.com/post/185611d5.html"><meta property="og:site_name" content="Cyan"><meta property="og:description" content="前言看这篇文章之前，我们不妨自问一下，我们为什么要去学习算法？这个对我们有什么好处？  学习算法可以开拓我们的思维，让我们的逻辑更加严谨 学习算法是成为一名优秀的开发者的途径之一 可以高质、高效地完成我们业务上的需求    排序算法冒泡排序 依次比较相邻的两个元素，根据大小互换位置，保证每一次比较大的数都在最后 重复n+1次，就可完成排序    1234567891011121314&#x2F;&#x2F; 时间复杂"><meta property="og:locale" content="zh_CN"><meta property="og:image" content="https://ali-oss.xmwpro.com/global/avatar.jpg"><meta property="article:published_time" content="2022-08-18T12:57:09.000Z"><meta property="article:modified_time" content="2023-06-26T09:26:36.564Z"><meta property="article:author" content="Cyan"><meta property="article:tag" content="JavaScript"><meta property="article:tag" content="算法"><meta name="twitter:card" content="summary"><meta name="twitter:image" content="https://ali-oss.xmwpro.com/global/avatar.jpg"><link rel="shortcut icon" href="https://ali-oss.xmwpro.com/global/favicon.ico"><link rel="canonical" href="https://xmwpro.com/post/185611d5.html"><link rel="preconnect" href="//cdn.jsdelivr.net"><link rel="preconnect" href="//www.google-analytics.com" crossorigin=""><link rel="preconnect" href="//hm.baidu.com"><meta name="baidu-site-verification" content="codeva-yHszJZWbvj"><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://ali-oss.xmwpro.com/cdn/css/all.min.css" media="print" onload='this.media="all"'><link rel="stylesheet" href="https://ali-oss.xmwpro.com/cdn/css/snackbar.min.css" media="print" onload='this.media="all"'><link rel="stylesheet" href="https://ali-oss.xmwpro.com/cdn/css/fancybox.css" media="print" onload='this.media="all"'><script>var _hmt=_hmt||[];!function(){var e=document.createElement("script");e.src="https://hm.baidu.com/hm.js?81fae81fdc8992b3e6ca314f289131e8";var t=document.getElementsByTagName("script")[0];t.parentNode.insertBefore(e,t)}()</script><script async src="https://www.googletagmanager.com/gtag/js?id=G-2P0LMHZNDD"></script><script>function gtag(){dataLayer.push(arguments)}window.dataLayer=window.dataLayer||[],gtag("js",new Date),gtag("config","G-2P0LMHZNDD")</script><script>const GLOBAL_CONFIG={root:"/",algolia:{appId:"2Q4I5JDAJR",apiKey:"2ec9f676fd9c568eb0abedad38d16fe6",indexName:"Hexo",hits:{per_page:6},languages:{input_placeholder:"输入关键词快速查找",hits_empty:"找不到您查询的内容：${query}",hits_stats:"找到 ${hits} 条结果，用时 ${time} 毫秒"}},localSearch:void 0,translate:{defaultEncoding:2,translateDelay:0,msgToTraditionalChinese:"繁",msgToSimplifiedChinese:"簡"},noticeOutdate:void 0,highlight:{plugin:"highlighjs",highlightCopy:!0,highlightLang:!0,highlightHeightLimit:200},copy:{success:"复制成功",error:"复制错误",noSupport:"浏览器不支持"},relativeDate:{homepage:!1,post:!1},runtime:"天",date_suffix:{just:"刚刚",min:"分钟前",hour:"小时前",day:"天前",month:"个月前"},copyright:{limitCount:50,languages:{author:"作者: Cyan",link:"链接: ",source:"来源: Cyan",info:"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},lightbox:"fancybox",Snackbar:{chs_to_cht:"你已切换为繁体",cht_to_chs:"你已切换为简体",day_to_night:"你已切换为深色模式",night_to_day:"你已切换为浅色模式",bgLight:"var(--cyan-theme-color)",bgDark:"var(--cyan-theme-color)",position:"top-center"},source:{justifiedGallery:{js:"https://ali-oss.xmwpro.com/cdn/js/fjGallery.min.js",css:"https://ali-oss.xmwpro.com/cdn/css/fjGallery.css"}},isPhotoFigcaption:!0,islazyload:!0,isAnchor:!1,percent:{toc:!1,rightside:!0}}</script><script id="config-diff">var GLOBAL_CONFIG_SITE={title:"JavaScript 常见算法",isPost:!0,isHome:!1,isHighlightShrink:!1,isToc:!0,postUpdate:"2023-06-26 09:26:36"}</script><noscript><style>#nav{opacity:1}.justified-gallery img{opacity:1}#post-meta time,#recent-posts time{display:inline!important}</style></noscript><script>(e=>{e.saveToLocal={set:function(e,t,o){if(0===o)return;const n=864e5*o,a={value:t,expiry:(new Date).getTime()+n};localStorage.setItem(e,JSON.stringify(a))},get:function(e){const t=localStorage.getItem(e);if(!t)return;const o=JSON.parse(t);if(!((new Date).getTime()>o.expiry))return o.value;localStorage.removeItem(e)}},e.getScript=e=>new Promise(((t,o)=>{const n=document.createElement("script");n.src=e,n.async=!0,n.onerror=o,n.onload=n.onreadystatechange=function(){const e=this.readyState;e&&"loaded"!==e&&"complete"!==e||(n.onload=n.onreadystatechange=null,t())},document.head.appendChild(n)})),e.getCSS=e=>new Promise(((t,o)=>{const n=document.createElement("link");n.rel="stylesheet",n.href=e,n.onload=()=>t(),n.onerror=()=>o(),document.head.appendChild(n)})),e.activateDarkMode=function(){document.documentElement.setAttribute("data-theme","dark"),null!==document.querySelector('meta[name="theme-color"]')&&document.querySelector('meta[name="theme-color"]').setAttribute("content","#0d0d0d")},e.activateLightMode=function(){document.documentElement.setAttribute("data-theme","light"),null!==document.querySelector('meta[name="theme-color"]')&&document.querySelector('meta[name="theme-color"]').setAttribute("content","#ffffff")};const t=saveToLocal.get("theme"),o=(new Date).getHours();void 0===t?o<=6||o>=18?activateDarkMode():activateLightMode():"light"===t?activateLightMode():activateDarkMode();const n=saveToLocal.get("aside-status");void 0!==n&&("hide"===n?document.documentElement.classList.add("hide-aside"):document.documentElement.classList.remove("hide-aside"));/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)&&document.documentElement.classList.add("apple")})(window)</script><link rel="stylesheet" href="//at.alicdn.com/t/c/font_3348168_pqjhlyxfz9r.css" media="defer" onload='this.media="all"'><link rel="stylesheet" href="https://ali-oss.xmwpro.com/cdn/css/swiper-bundle.min.css"><link rel="stylesheet" href="https://ali-oss.xmwpro.com/cdn/css/tianli_gpt.css"><script src="https://ali-oss.xmwpro.com/cdn/js/swiper-bundle.min.js"></script><script data-pjax src="https://ali-oss.xmwpro.com/cdn/js/jquery-3.3.1.js"></script><script data-pjax src="https://ali-oss.xmwpro.com/cdn/js/echarts.min.js"></script><script charset="UTF-8" id="LA_COLLECT" src="https://sdk.51.la/js-sdk-pro.min.js"></script><script src="https://ali-oss.xmwpro.com/cdn/js/three.min.js"></script><link rel="stylesheet" href="https://ali-oss.xmwpro.com/cdn/css/font-awesome-animation.min.css" media="defer" onload='this.media="all"'><link rel="stylesheet" href="https://ali-oss.xmwpro.com/cdn/css/tag_plugins.css" media="defer" onload='this.media="all"'><link rel="stylesheet" href="https://ali-oss.xmwpro.com/cdn/css/animate.min.css" media="print" onload='this.media="screen"'><link rel="stylesheet" href="https://ali-oss.xmwpro.com/cdn/css/gitcalendar.css" media="print" onload='this.media="all"'><meta name="generator" content="Hexo 5.4.2"><link rel="alternate" href="/atom.xml" title="Cyan" type="application/atom+xml"></head><body><div id="loading-box" onclick="document.getElementById(&quot;loading-box&quot;).classList.add(&quot;loaded&quot;)"><div class="loading-bg"><div class="loading-img"></div><div class="loading-image-dot"></div></div></div><script>const preloader={endLoading:()=>{document.body.style.overflow="auto",document.getElementById("loading-box").classList.add("loaded")},initLoading:()=>{document.body.style.overflow="",document.getElementById("loading-box").classList.remove("loaded")}};window.addEventListener("load",(()=>{preloader.endLoading()})),document.addEventListener("pjax:send",(()=>{preloader.initLoading()})),document.addEventListener("pjax:complete",(()=>{preloader.endLoading()}))</script><link rel="stylesheet" href="https://ali-oss.xmwpro.com/cdn/css/progress_bar.css"><script src="https://ali-oss.xmwpro.com/cdn/js/pace.min.js"></script><div id="web_bg"></div><div id="music_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="" data-lazy-src="https://ali-oss.xmwpro.com/global/avatar.jpg" onerror='onerror=null,src="/img/friend_404.gif"' alt="avatar"></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">48</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">23</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">6</div></a></div><hr><div class="menus_items"><div class="menus_item"><a class="site-page group faa-parent animated-hover" href="javascript:void(0);" rel="external nofollow noreferrer"><i class="fa-fw faa-tada fas fa-book"></i> <span>文库</span></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/archives/"><i class="fa-fw faa-tada fa-solid fa-box-archive"></i> <span>全部文章</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/tags/"><i class="fa-fw faa-tada fas fa-tags"></i> <span>标签</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/categories/"><i class="fa-fw faa-tada fas fa-shapes"></i> <span>分类</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover" href="javascript:void(0);" rel="external nofollow noreferrer"><i class="fa-fw faa-tada fab fa-artstation"></i> <span>社交</span></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/link/"><i class="fa-fw faa-tada fa-solid fa-link"></i> <span>友人帐</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/fcircle/"><i class="fa-fw faa-tada fa-solid fa-user-group"></i> <span>朋友圈</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/guestbook/"><i class="fa-fw faa-tada fa-solid fa-envelope"></i> <span>留言板</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover" href="javascript:void(0);" rel="external nofollow noreferrer"><i class="fa-fw faa-tada fas fa-coffee"></i> <span>休闲</span></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/music/"><i class="fa-fw faa-tada fa-solid fa-music"></i> <span>音乐馆</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/photoAlbum/"><i class="fa-fw faa-tada fa-solid fa-camera"></i> <span>相册</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/essay/"><i class="fa-fw faa-tada fa-solid fa-message"></i> <span>哔哔</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover" href="javascript:void(0);" rel="external nofollow noreferrer"><i class="fa-fw faa-tada fa-solid fa-earth-asia"></i> <span>本站</span></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/analysis/"><i class="fa-fw faa-tada fa-solid fa-chart-simple"></i> <span>博客统计</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/about/"><i class="fa-fw faa-tada fa-regular fa-address-card"></i> <span>关于我</span></a></li></ul></div></div></div></div><div class="canvas-container" id="canvas"></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image:url('https://ali-oss.xmwpro.com/posts/post_cover29.jpg')"><nav id="nav"><span id="blog-info"><div class="back-home-button" tabindex="-1"><i class="back-home-button-icon fas fa-grip-vertical"></i><div class="back-menu-list-groups"><div class="back-menu-list-group"><div class="back-menu-list-title">社交</div><div class="back-menu-list"><a class="back-menu-item" href="https://xmwpro.com/" title="白雾茫茫丶" target="_blank" one-link-mark="yes"><img class="back-menu-item-icon" src="" data-lazy-src="https://ali-oss.xmwpro.com/global/avatar.jpg"><span class="back-menu-item-text">白雾茫茫丶</span></a><a class="back-menu-item" href="https://github.com/Cyan-Xmw/" rel="external nofollow noreferrer" title="Github" target="_blank" one-link-mark="yes"><i class="iconfont cyan-gitHub"></i><span class="back-menu-item-text">Github</span></a><a class="back-menu-item" href="https://gitee.com/Cyan-Xmw/" rel="external nofollow noreferrer" title="Gitee" target="_blank" one-link-mark="yes"><i class="iconfont cyan-gitee"></i><span class="back-menu-item-text">Gitee</span></a><a class="back-menu-item" href="https://juejin.cn/user/1917147257534279/" rel="external nofollow noreferrer" title="掘金" target="_blank" one-link-mark="yes"><i class="iconfont cyan-juejin"></i><span class="back-menu-item-text">掘金</span></a></div></div><div class="back-menu-list-group"><div class="back-menu-list-title">项目</div><div class="back-menu-list"><a class="back-menu-item" href="https://docs.xmwpro.com/" rel="external nofollow noreferrer" title="Cyan Docs" target="_blank" one-link-mark="yes"><img class="back-menu-item-icon" src="" data-lazy-src="https://ali-oss.xmwpro.com/project/xmw-dumi-docs/logo.svg"><span class="back-menu-item-text">Cyan Docs</span></a><a class="back-menu-item" href="http://react.xmwpro.com/" rel="external nofollow noreferrer" title="Xmw-Admin" target="_blank" one-link-mark="yes"><img class="back-menu-item-icon" src="" data-lazy-src="https://ali-oss.xmwpro.com/pages/resource/xmw-admin.svg"><span class="back-menu-item-text">Xmw-Admin</span></a><a class="back-menu-item" href="http://vue3.xmwpro.com/" rel="external nofollow noreferrer" title="Vue3-Admin" target="_blank" one-link-mark="yes"><img class="back-menu-item-icon" src="" data-lazy-src="https://ali-oss.xmwpro.com/project/vue3-admin/logo.png"><span class="back-menu-item-text">Vue3-Admin</span></a><a class="back-menu-item" href="http://vue2.xmwpro.com/" rel="external nofollow noreferrer" title="Vue2-Admin" target="_blank" one-link-mark="yes"><img class="back-menu-item-icon" src="" data-lazy-src="https://ali-oss.xmwpro.com/project/vue2-admin/logo.svg"><span class="back-menu-item-text">Vue2-Admin</span></a><a class="back-menu-item" href="https://ele-plus-form.xmwpro.com/" rel="external nofollow noreferrer" title="vue3-form" target="_blank" one-link-mark="yes"><img class="back-menu-item-icon" src="" data-lazy-src="https://ali-oss.xmwpro.com/pages/resource/vue.svg"><span class="back-menu-item-text">vue3-form</span></a><a class="back-menu-item" href="https://ele-plus-table.xmwpro.com/" rel="external nofollow noreferrer" title="vue3-table" target="_blank" one-link-mark="yes"><img class="back-menu-item-icon" src="" data-lazy-src="https://ali-oss.xmwpro.com/pages/resource/vue.svg"><span class="back-menu-item-text">vue3-table</span></a></div></div></div></div><a id="site-name" href="/"><div class="title">Cyan</div><i class="fa-solid fa-house"></i></a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page group faa-parent animated-hover" href="javascript:void(0);" rel="external nofollow noreferrer"><i class="fa-fw faa-tada fas fa-book"></i> <span>文库</span></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/archives/"><i class="fa-fw faa-tada fa-solid fa-box-archive"></i> <span>全部文章</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/tags/"><i class="fa-fw faa-tada fas fa-tags"></i> <span>标签</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/categories/"><i class="fa-fw faa-tada fas fa-shapes"></i> <span>分类</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover" href="javascript:void(0);" rel="external nofollow noreferrer"><i class="fa-fw faa-tada fab fa-artstation"></i> <span>社交</span></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/link/"><i class="fa-fw faa-tada fa-solid fa-link"></i> <span>友人帐</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/fcircle/"><i class="fa-fw faa-tada fa-solid fa-user-group"></i> <span>朋友圈</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/guestbook/"><i class="fa-fw faa-tada fa-solid fa-envelope"></i> <span>留言板</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover" href="javascript:void(0);" rel="external nofollow noreferrer"><i class="fa-fw faa-tada fas fa-coffee"></i> <span>休闲</span></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/music/"><i class="fa-fw faa-tada fa-solid fa-music"></i> <span>音乐馆</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/photoAlbum/"><i class="fa-fw faa-tada fa-solid fa-camera"></i> <span>相册</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/essay/"><i class="fa-fw faa-tada fa-solid fa-message"></i> <span>哔哔</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover" href="javascript:void(0);" rel="external nofollow noreferrer"><i class="fa-fw faa-tada fa-solid fa-earth-asia"></i> <span>本站</span></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/analysis/"><i class="fa-fw faa-tada fa-solid fa-chart-simple"></i> <span>博客统计</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/about/"><i class="fa-fw faa-tada fa-regular fa-address-card"></i> <span>关于我</span></a></li></ul></div></div><center id="name-container"><span id="page-name" href="javascript:void(0);">PAGE_NAME</span></center></div><div id="nav-right"><div class="nav-button" id="search-button"><a class="social-icon search" href="javascript:void(0);" rel="external nofollow noreferrer" title="全局搜索"><i class="fas fa-search fa-fw"></i></a></div><div class="nav-button"><a class="social-icon" target="_blank" rel="noopener external nofollow noreferrer" href="https://travellings.cn/go.html" title="离开这里并访问下一个博客「开往服务」"><i class="fa-solid fa-subway"></i></a></div><div class="nav-button"><a class="social-icon random-post" href="javascript:toRandomPost();" rel="external nofollow noreferrer" title="随机前往一个文章"><i class="fa-solid fa-dice"></i></a></div><div class="nav-button" id="darkmode_navswitch"><a class="darkmode_switchbutton" type="button" title="浅色和深色模式转换" onclick="document.getElementById(&quot;darkmode&quot;).click()"><i class="fas fa-moon isMoon"></i><i class="fas fa-sun isSun"></i></a></div><div class="nav-button" id="go-up" title="回到顶部"><a class="totopbtn" href="javascript:void(0);" rel="external nofollow noreferrer"><span class="scroll-percent" onclick="btf.scrollToDest(0,500)"></span><i class="fas fa-arrow-up" onclick="btf.scrollToDest(0,500)"></i></a></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);" rel="external nofollow noreferrer"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><div class="post-container"><div class="post-container-categories"><a class="categories-link" href="/categories/%E6%95%B0%E6%8D%AE%E7%AE%97%E6%B3%95/">数据算法</a></div><div class="post-container-tags"><a class="tags-link" href="/tags/JavaScript/"><span class="tags-punctuation">#</span><span class="tags-name">JavaScript</span></a><a class="tags-link" href="/tags/%E7%AE%97%E6%B3%95/"><span class="tags-punctuation">#</span><span class="tags-name">算法</span></a></div></div><h1 class="post-title">JavaScript 常见算法</h1><div id="post-meta"><div class="meta-secondline"><div class="post-meta-common post-meta-date" title="发表于 2022-08-18 12:57:09"><i class="fas fa-calendar fa-fw post-meta-icon"></i><time class="post-meta-date-created" datetime="2022-08-18T12:57:09.000Z">08-18</time></div><div class="post-meta-common post-meta-date" title="更新于 2023-06-26 09:26:36"><i class="fas fa-history fa-fw post-meta-icon"></i><time class="post-meta-date-updated" datetime="2022-08-18T12:57:09.000Z">06-26</time></div><div class="post-meta-common post-meta-wordcount" title="字数总计 1.8k"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="word-count">1.8k</span></div><div class="post-meta-common post-meta-read-time" title="阅读时长 7分钟"><i class="far fa-clock fa-fw post-meta-icon"></i><span>7分钟</span></div><div class="post-meta-common post-meta-commentcount" title="评论数" onclick='cyan.scrollTo("#post-comment")'><i class="fa-solid fa-comment fa-fw post-meta-icon"></i><a href="/post/185611d5.html#post-comment"><span id="twikoo-count"><i class="fa-solid fa-spinner fa-spin"></i></span></a></div></div></div></div><section class="main-hero-waves-area waves-area"><svg class="waves-svg" xmlns="http://www.w3.org/2000/svg" xlink="http://www.w3.org/1999/xlink" viewBox="0 24 150 28" preserveAspectRatio="none" shape-rendering="auto"><defs><path id="gentle-wave" d="M-160 44c30 0 58-18 88-18s58 18 88 18 58-18 88-18 58 18 88 18v44h-352Z"></path></defs><g class="parallax"><use href="#gentle-wave" x="48" y="0"></use><use href="#gentle-wave" x="48" y="3"></use><use href="#gentle-wave" x="48" y="5"></use><use href="#gentle-wave" x="48" y="7"></use></g></svg></section></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><div class="tip theme fa-house"><p>看这篇文章之前，我们不妨自问一下，我们为什么要去学习算法？这个对我们有什么好处？</p><ol><li>学习算法可以开拓我们的思维，让我们的逻辑更加严谨</li><li>学习算法是成为一名优秀的开发者的途径之一</li><li>可以高质、高效地完成我们业务上的需求</li></ol></div><h2 id="排序算法"><a href="#排序算法" class="headerlink" title="排序算法"></a>排序算法</h2><h3 id="冒泡排序"><a href="#冒泡排序" class="headerlink" title="冒泡排序"></a>冒泡排序</h3><ol><li>依次比较相邻的两个元素，根据大小互换位置，保证每一次比较大的数都在最后</li><li>重复n+1次，就可完成排序</li></ol><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 时间复杂度 O(n ^ 2) n为数组长度</span></span><br><span class="line"><span class="comment">// 空间复杂度 O(1)</span></span><br><span class="line"><span class="title class_">Array</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">bubbleSort</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">  <span class="comment">// 获取当前的数组</span></span><br><span class="line">  <span class="keyword">const</span> ctx = <span class="variable language_">this</span></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; ctx.<span class="property">length</span> - <span class="number">1</span>; i++) &#123;</span><br><span class="line">      <span class="keyword">for</span> (<span class="keyword">let</span> j = <span class="number">0</span>; j &lt; ctx.<span class="property">length</span> - <span class="number">1</span> - i; j++) &#123;</span><br><span class="line">          <span class="comment">// 判断后面一个数是否大于前面的，如果是则交换位置</span></span><br><span class="line">          <span class="keyword">if</span> (ctx[j] &gt; ctx[j + <span class="number">1</span>]) &#123;</span><br><span class="line">              [ctx[j], ctx[j + <span class="number">1</span>]] = [ctx[j + <span class="number">1</span>], ctx[j]]</span><br><span class="line">          &#125;</span><br><span class="line">      &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>测试：<br></p><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> arr = [<span class="number">3</span>, <span class="number">6</span>, <span class="number">12</span>, <span class="number">65</span>, <span class="number">23</span>, <span class="number">2</span>]</span><br><span class="line">arr.<span class="title function_">bubbleSort</span>()</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(arr)</span><br></pre></td></tr></table></figure><p></p><h3 id="选择排序"><a href="#选择排序" class="headerlink" title="选择排序"></a>选择排序</h3><ol><li>找到数组中最小的值，把它放到第一位，再找到第二小的值，放到第二位</li><li>重复上次操作n-1次</li></ol><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 时间复杂度：O(n ^ 2) n为数组长度</span></span><br><span class="line"><span class="comment">// 空间复杂度：O(1)</span></span><br><span class="line"><span class="title class_">Array</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">selectionSort</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">  <span class="comment">// 获取当前的数组</span></span><br><span class="line">  <span class="keyword">const</span> ctx = <span class="variable language_">this</span></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; ctx.<span class="property">length</span> - <span class="number">1</span>; i++) &#123;</span><br><span class="line">      <span class="comment">// 最小值的索引</span></span><br><span class="line">      <span class="keyword">let</span> indexMin = i</span><br><span class="line">      <span class="keyword">for</span> (<span class="keyword">let</span> j = i; j &lt; ctx.<span class="property">length</span>; j++) &#123;</span><br><span class="line">          <span class="comment">// 如果当前元素小于indexMin的值，则更新indexMin</span></span><br><span class="line">          <span class="keyword">if</span> (ctx[j] &lt; ctx[indexMin]) &#123;</span><br><span class="line">              indexMin = j</span><br><span class="line">          &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">// 避免自己和自己交换</span></span><br><span class="line">      <span class="keyword">if</span> (indexMin !== i) &#123;</span><br><span class="line">          <span class="comment">// 进行数据交换</span></span><br><span class="line">          [ctx[i], ctx[indexMin]] = [ctx[indexMin], ctx[i]]</span><br><span class="line">      &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>测试：<br></p><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> arr = [<span class="number">3</span>, <span class="number">6</span>, <span class="number">12</span>, <span class="number">65</span>, <span class="number">23</span>, <span class="number">2</span>]</span><br><span class="line">arr.<span class="title function_">selectionSort</span>()</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(arr)</span><br></pre></td></tr></table></figure><p></p><h3 id="插入排序"><a href="#插入排序" class="headerlink" title="插入排序"></a>插入排序</h3><ol><li>从数组第二个数开始往前比较，如它大就往后排</li><li>依次类推到最后一个数</li></ol><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 时间复杂度 O(n ^ 2)</span></span><br><span class="line">  <span class="title class_">Array</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">insertionSort</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">      <span class="comment">// 获取当前的数组</span></span><br><span class="line">      <span class="keyword">const</span> ctx = <span class="variable language_">this</span></span><br><span class="line">      <span class="comment">// 插入排序数组长度至少是2</span></span><br><span class="line">      <span class="keyword">if</span> (ctx.<span class="property">length</span> &lt; <span class="number">1</span>) &#123;</span><br><span class="line">          <span class="keyword">return</span> ctx</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">// 循环遍历，从第一位开始</span></span><br><span class="line">      <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">1</span>; i &lt; ctx.<span class="property">length</span>; i++) &#123;</span><br><span class="line">          <span class="comment">// 获取数组第一位元素</span></span><br><span class="line">          <span class="keyword">let</span> temp = ctx[i]</span><br><span class="line">          <span class="comment">// 获取当前索引</span></span><br><span class="line">          <span class="keyword">let</span> j = i</span><br><span class="line">          <span class="keyword">while</span> (j &gt; <span class="number">0</span>) &#123;</span><br><span class="line">              <span class="comment">// 当前面的数小于后面的数则交换位置</span></span><br><span class="line">              <span class="keyword">if</span> (ctx[j - <span class="number">1</span>] &gt; temp) &#123;</span><br><span class="line">                  [ctx[j - <span class="number">1</span>], ctx[j]] = [ctx[j], ctx[j - <span class="number">1</span>]]</span><br><span class="line">              &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                  <span class="comment">// 如果条件不符合则跳出当前循环</span></span><br><span class="line">                  <span class="keyword">break</span></span><br><span class="line">              &#125;</span><br><span class="line">              <span class="comment">// 递减</span></span><br><span class="line">              j--;</span><br><span class="line">          &#125;</span><br><span class="line">      &#125;</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure><p>测试：<br></p><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> arr = [<span class="number">3</span>, <span class="number">6</span>, <span class="number">12</span>, <span class="number">65</span>, <span class="number">23</span>, <span class="number">2</span>]</span><br><span class="line">arr.<span class="title function_">insertionSort</span>()</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(arr)</span><br></pre></td></tr></table></figure><p></p><h3 id="归并排序"><a href="#归并排序" class="headerlink" title="归并排序"></a>归并排序</h3><ol><li>把数组劈成两半 在递归的对子数组进行分操作，直到分成一个个单独的数</li></ol><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 时间复杂度 O(nlogn) 分需要劈开数组，所以是logn， 合则是n</span></span><br><span class="line"><span class="comment">// 空间复杂度 O(n)</span></span><br><span class="line"><span class="title class_">Array</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">mergeSort</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">    <span class="comment">// 获取当前数组</span></span><br><span class="line">    <span class="keyword">const</span> ctx = <span class="variable language_">this</span></span><br><span class="line">    <span class="comment">// 判断数组长度是否大于1</span></span><br><span class="line">    <span class="keyword">if</span> (ctx.<span class="property">length</span> &lt;= <span class="number">1</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> ctx</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">const</span> <span class="title function_">recursiveArr</span> = (<span class="params">arr</span>) =&gt; &#123;</span><br><span class="line">        <span class="comment">// 递归结束条件</span></span><br><span class="line">        <span class="keyword">if</span> (arr.<span class="property">length</span> === <span class="number">1</span>) <span class="keyword">return</span> arr</span><br><span class="line">        <span class="comment">// 获取数组中间的索引</span></span><br><span class="line">        <span class="keyword">const</span> indexMid = arr.<span class="property">length</span> &gt;&gt; <span class="number">1</span></span><br><span class="line">        <span class="comment">// 截取左右两边的数组</span></span><br><span class="line">        <span class="keyword">const</span> leftTemp = arr.<span class="title function_">slice</span>(<span class="number">0</span>, indexMid)</span><br><span class="line">        <span class="keyword">const</span> rightTemp = arr.<span class="title function_">slice</span>(indexMid)</span><br><span class="line">        <span class="comment">// 对 左右两侧的数组进行递归，得到两个有序数组</span></span><br><span class="line">        <span class="keyword">const</span> orderLeft = <span class="title function_">recursiveArr</span>(leftTemp)</span><br><span class="line">        <span class="keyword">const</span> orderRight = <span class="title function_">recursiveArr</span>(rightTemp)</span><br><span class="line">        <span class="comment">// 定义一个空数组</span></span><br><span class="line">        <span class="keyword">let</span> result = []</span><br><span class="line">        <span class="comment">// 遍历循环</span></span><br><span class="line">        <span class="keyword">while</span> (orderLeft.<span class="property">length</span> || orderRight.<span class="property">length</span>) &#123;</span><br><span class="line">            <span class="comment">// 如果两个数组一直有数据，则把值小的出队</span></span><br><span class="line">            <span class="keyword">if</span> (orderLeft.<span class="property">length</span> &amp;&amp; orderRight.<span class="property">length</span>) &#123;</span><br><span class="line">                <span class="comment">// 值小的出队</span></span><br><span class="line">                result.<span class="title function_">push</span>(orderLeft[<span class="number">0</span>] &lt; orderRight[<span class="number">0</span>] ? orderLeft.<span class="title function_">shift</span>() : orderRight.<span class="title function_">shift</span>())</span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (orderLeft.<span class="property">length</span>) &#123;</span><br><span class="line">                <span class="comment">// 把左边的队友放入数组</span></span><br><span class="line">                result.<span class="title function_">push</span>(orderLeft.<span class="title function_">shift</span>())</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="comment">// 把右边的队友放入数组</span></span><br><span class="line">                result.<span class="title function_">push</span>(orderRight.<span class="title function_">shift</span>())</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> result</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 对当前数组进行递归处理</span></span><br><span class="line">    <span class="keyword">const</span> finalResult = <span class="title function_">recursiveArr</span>(ctx)</span><br><span class="line">    <span class="comment">// 把当前结果放入原数组</span></span><br><span class="line">    finalResult.<span class="title function_">forEach</span>(<span class="function">(<span class="params">element, index</span>) =&gt;</span> ctx[index] = element)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>测试：<br></p><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> arr = [<span class="number">3</span>, <span class="number">6</span>, <span class="number">12</span>, <span class="number">65</span>, <span class="number">23</span>, <span class="number">2</span>]</span><br><span class="line">arr.<span class="title function_">mergeSort</span>()</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(arr)</span><br></pre></td></tr></table></figure><p></p><h3 id="合并两个有序链表"><a href="#合并两个有序链表" class="headerlink" title="合并两个有序链表"></a>合并两个有序链表</h3><ol><li>把两个树合并为有序数组，再对有序数组进行合并， 直到全部子数组合并为一个完整的数组</li></ol><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 时间复杂度O(n) n为链表1和链表2的长度之和</span></span><br><span class="line"><span class="comment">// 空间复杂度O(1)</span></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">mergeTwoLists</span> = (<span class="params">list1, list2</span>) =&gt; &#123;</span><br><span class="line">    <span class="comment">// 定义一个新链表，作为返回值</span></span><br><span class="line">    <span class="keyword">const</span> result = &#123;</span><br><span class="line">        <span class="attr">val</span>: <span class="number">0</span>,</span><br><span class="line">        <span class="attr">next</span>: <span class="literal">null</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 创建一个指向新链表的指针</span></span><br><span class="line">    <span class="keyword">const</span> p = result</span><br><span class="line">    <span class="comment">// 创建两个指向链表的指针</span></span><br><span class="line">    <span class="keyword">const</span> p1 = list1</span><br><span class="line">    <span class="keyword">const</span> p2 = list2</span><br><span class="line">    <span class="comment">// 遍历循环</span></span><br><span class="line">    <span class="keyword">while</span> (p1 &amp;&amp; p2) &#123;</span><br><span class="line">        <span class="comment">// 判断两个链表的值大小</span></span><br><span class="line">        <span class="keyword">if</span> (p1.<span class="property">val</span> &lt; p2.<span class="property">val</span>) &#123;</span><br><span class="line">            <span class="comment">// 往p插入一个链表</span></span><br><span class="line">            p.<span class="property">next</span> = p1</span><br><span class="line">            <span class="comment">// p1需要往后移动</span></span><br><span class="line">            p1 = p1.<span class="property">next</span></span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">// 同上</span></span><br><span class="line">            p.<span class="property">next</span> = p2</span><br><span class="line">            p2 = p2.<span class="property">next</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 如果p1和p2还有值，就把后面的值全部接入新链表</span></span><br><span class="line">    <span class="keyword">if</span> (p1) &#123;</span><br><span class="line">        p1 = p1.<span class="property">next</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (p2) &#123;</span><br><span class="line">        p2 = p2.<span class="property">next</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> result.<span class="property">next</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h3 id="快速排序"><a href="#快速排序" class="headerlink" title="快速排序"></a>快速排序</h3><ol><li>从数组中任意选择一个基准，比基准小的放在基准前面，比基准大的放在基准后面</li><li>递归对基准前后的的子数组进行分区</li></ol><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 时间复杂度 O(nlogN)</span></span><br><span class="line"><span class="comment">// 空间复杂度 O(1)</span></span><br><span class="line"><span class="title class_">Array</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">quickSort</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">    <span class="comment">// 获取当前数组</span></span><br><span class="line">    <span class="keyword">const</span> ctx = <span class="variable language_">this</span></span><br><span class="line">    <span class="comment">// 判断数组长度，小于1的就不用排序了</span></span><br><span class="line">    <span class="keyword">if</span> (ctx.<span class="property">length</span> &lt;= <span class="number">1</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> ctx</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 定义一个递归函数</span></span><br><span class="line">    <span class="keyword">const</span> <span class="title function_">recursive</span> = arr =&gt; &#123;</span><br><span class="line">        <span class="comment">// 如果数组长度小于1就不用排序</span></span><br><span class="line">        <span class="keyword">if</span> (arr.<span class="property">length</span> &lt;= <span class="number">1</span>) <span class="keyword">return</span> arr</span><br><span class="line">        <span class="comment">// 获取一个基准元素</span></span><br><span class="line">        <span class="keyword">const</span> benchmark = arr[<span class="number">0</span>]</span><br><span class="line">        <span class="comment">// 定义基准两侧的数组</span></span><br><span class="line">        <span class="keyword">const</span> leftB = []</span><br><span class="line">        <span class="keyword">const</span> rightB = []</span><br><span class="line">        <span class="comment">// for遍历循环</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">1</span>; i &lt; arr.<span class="property">length</span>; i++) &#123;</span><br><span class="line">            <span class="comment">// 判断元素唯一基准的左右</span></span><br><span class="line">            <span class="keyword">if</span> (arr[i] &lt; benchmark) &#123;</span><br><span class="line">                leftB.<span class="title function_">push</span>(arr[i])</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                rightB.<span class="title function_">push</span>(arr[i])</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 递归调用两边的数组</span></span><br><span class="line">        <span class="keyword">return</span> [...<span class="title function_">recursive</span>(leftB), benchmark, ...<span class="title function_">recursive</span>(rightB)]</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 执行递归后的返回值</span></span><br><span class="line">    <span class="keyword">const</span> result = <span class="title function_">recursive</span>(ctx)</span><br><span class="line">    <span class="comment">// 把当前结果放入原数组</span></span><br><span class="line">    result.<span class="title function_">forEach</span>(<span class="function">(<span class="params">element, index</span>) =&gt;</span> ctx[index] = element)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>测试：<br></p><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> arr = [<span class="number">3</span>, <span class="number">6</span>, <span class="number">12</span>, <span class="number">65</span>, <span class="number">23</span>, <span class="number">2</span>]</span><br><span class="line">arr.<span class="title function_">quickSort</span>()</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(arr)</span><br></pre></td></tr></table></figure><p></p><h2 id="搜索算法"><a href="#搜索算法" class="headerlink" title="搜索算法"></a>搜索算法</h2><h3 id="顺序搜索"><a href="#顺序搜索" class="headerlink" title="顺序搜索"></a>顺序搜索</h3><ol><li>从头开始搜索数组中的某个元素，比如数组的 <code>indexOf</code> 方法。</li></ol><h3 id="二分搜索"><a href="#二分搜索" class="headerlink" title="二分搜索"></a>二分搜索</h3><ol><li>从数组中的中间位置开始搜索，如果中间元素正好是目标值，则搜索结束</li><li>如果目标值大于或者小于中间元素，则在大于或者小于中间元素的那一半数组中搜索</li><li>数组必须是有序的，如不是则需要先进行排序</li></ol><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 时间复杂度：O(log n)</span></span><br><span class="line"><span class="comment">// 空间复杂度：O(1)</span></span><br><span class="line"><span class="title class_">Array</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">binalySearch</span> = <span class="keyword">function</span> (<span class="params">element</span>) &#123;</span><br><span class="line">    <span class="comment">// 获取当前数组</span></span><br><span class="line">    <span class="keyword">const</span> ctx = <span class="variable language_">this</span></span><br><span class="line">    <span class="comment">// 获取最小索引</span></span><br><span class="line">    <span class="keyword">let</span> minIndex = <span class="number">0</span></span><br><span class="line">    <span class="comment">// 获取最大索引</span></span><br><span class="line">    <span class="keyword">let</span> maxIndex = ctx.<span class="property">length</span> - <span class="number">1</span></span><br><span class="line">    <span class="comment">// 循环遍历</span></span><br><span class="line">    <span class="keyword">while</span> (minIndex &lt;= maxIndex) &#123;</span><br><span class="line">        <span class="comment">// 获取中间元素索引</span></span><br><span class="line">        <span class="keyword">let</span> midIndex = (minIndex + maxIndex) &gt;&gt; <span class="number">1</span></span><br><span class="line">        <span class="comment">// 判断元素是否大于中间索引,如果大于就把最小索引往中间索引的下一个</span></span><br><span class="line">        <span class="keyword">if</span> (element &gt; ctx[midIndex]) &#123;</span><br><span class="line">            <span class="comment">// 则最小索引往前</span></span><br><span class="line">            minIndex = midIndex + <span class="number">1</span></span><br><span class="line">            <span class="comment">// 判断元素是否小于中间索引,如果大于就把最大索引往中间索引的前一个</span></span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (element &lt; ctx[midIndex]) &#123;</span><br><span class="line">            maxIndex = midIndex - <span class="number">1</span></span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">// 如果中间的元素正式要查找的元素</span></span><br><span class="line">            <span class="keyword">return</span> midIndex</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 如果都找不到，则返回-1</span></span><br><span class="line">    <span class="keyword">return</span> -<span class="number">1</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>测试：</p><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> arr = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>]</span><br><span class="line"><span class="keyword">const</span> index = arr.<span class="title function_">binalySearch</span>(<span class="number">7</span>)</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(index)</span><br></pre></td></tr></table></figure></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者:</span> <span class="post-copyright-info"><a href="https://xmwpro.com">Cyan</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接:</span> <span class="post-copyright-info"><a href="https://xmwpro.com/post/185611d5.html">https://xmwpro.com/post/185611d5.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明:</span> <span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow noreferrer" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://xmwpro.com" target="_blank">Cyan</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/JavaScript/"><span class="tags-punctuation">#</span><span class="tags-name">JavaScript</span><sup>4</sup></a><a class="post-meta__tags" href="/tags/%E7%AE%97%E6%B3%95/"><span class="tags-punctuation">#</span><span class="tags-name">算法</span><sup>2</sup></a></div><div class="post_share"><div class="social-share" data-image="https://ali-oss.xmwpro.com/global/avatar.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://ali-oss.xmwpro.com/cdn/css/share.min.css" media="print" onload='this.media="all"'><script src="https://ali-oss.xmwpro.com/cdn/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://ali-oss.xmwpro.com/global/wx-pay.jpeg" rel="external nofollow noreferrer" target="_blank"><img class="post-qr-code-img" src="" data-lazy-src="https://ali-oss.xmwpro.com/global/wx-pay.jpeg" alt="微信"></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="https://ali-oss.xmwpro.com/global/zfb-pay.jpeg" rel="external nofollow noreferrer" target="_blank"><img class="post-qr-code-img" src="" data-lazy-src="https://ali-oss.xmwpro.com/global/zfb-pay.jpeg" alt="支付宝"></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/post/65e63605.html" title="vue-router钩子函数和具体的执行流程"><img class="cover" src="" data-lazy-src="https://ali-oss.xmwpro.com/posts/post_cover10.jpg" onerror='onerror=null,src="/img/404.jpg"' alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">vue-router钩子函数和具体的执行流程</div></div></a></div><div class="next-post pull-right"><a href="/post/b7a80595.html" title="大厂面试经典算法题"><img class="cover" src="" data-lazy-src="https://ali-oss.xmwpro.com/posts/post_cover36.jpg" onerror='onerror=null,src="/img/404.jpg"' alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">大厂面试经典算法题</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list swiper"><div class="swiper-wrapper"><div class="swiper-slide related-item"><a href="/post/b7a80595.html" title="大厂面试经典算法题"><img class="cover" src="" data-lazy-src="https://ali-oss.xmwpro.com/posts/post_cover47.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-20</div><div class="title">大厂面试经典算法题</div></div></a></div><div class="swiper-slide related-item"><a href="/post/65e63605.html" title="vue-router钩子函数和具体的执行流程"><img class="cover" src="" data-lazy-src="https://ali-oss.xmwpro.com/posts/post_cover6.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-17</div><div class="title">vue-router钩子函数和具体的执行流程</div></div></a></div><div class="swiper-slide related-item"><a href="/post/2610edc0.html" title="经典 JavaScript 手撕面试题"><img class="cover" src="" data-lazy-src="https://ali-oss.xmwpro.com/posts/post_cover46.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-02</div><div class="title">经典 JavaScript 手撕面试题</div></div></a></div></div><div class="related-swiper-scrollbar"></div></div></div><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i> <span>评论</span></div><div class="comment-tips">您无需删除空行，直接评论以获取最佳展示效果</div></div><div class="comment-wrap"><div><div id="twikoo-wrap"></div></div></div><div class="barrageswiper"><div class="swiper"><div class="swiper-wrapper"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-info-my"><div class="card-info-my-avatar"><img src="" data-lazy-src="https://ali-oss.xmwpro.com/global/avatar.jpg" onerror='this.onerror=null,this.src="/img/friend_404.gif"' alt="avatar"></div><div class="card-info-my-name"><div class="card-info-my-name-welcome"></div><div class="card-info-my-name-text">谢明伟</div></div></div><div class="card-info-content"><b>记录学习、生活和有趣的事</b></div><div class="card-info-announcement">好好吃饭🍣 好好睡觉💤 敲敲代码💻 谈谈恋爱💑</div><div class="card-info-social"><div class="card-info-social-icon"><a class="social-icon" href="https://github.com/Cyan-Xmw" rel="external nofollow noreferrer" target="_blank" title="Github"><i class="iconfont cyan-github-fill"></i></a></div><a class="card-info-social-more" href="/about/"><i class="fas fa-circle-chevron-right"></i><span class="card-info-social-more-text">了解更多</span></a></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%89%8D%E8%A8%80"><span class="toc-number">1.</span> <span class="toc-text">前言</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%8E%92%E5%BA%8F%E7%AE%97%E6%B3%95"><span class="toc-number">2.</span> <span class="toc-text">排序算法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%86%92%E6%B3%A1%E6%8E%92%E5%BA%8F"><span class="toc-number">2.1.</span> <span class="toc-text">冒泡排序</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%80%89%E6%8B%A9%E6%8E%92%E5%BA%8F"><span class="toc-number">2.2.</span> <span class="toc-text">选择排序</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%8F%92%E5%85%A5%E6%8E%92%E5%BA%8F"><span class="toc-number">2.3.</span> <span class="toc-text">插入排序</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BD%92%E5%B9%B6%E6%8E%92%E5%BA%8F"><span class="toc-number">2.4.</span> <span class="toc-text">归并排序</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%90%88%E5%B9%B6%E4%B8%A4%E4%B8%AA%E6%9C%89%E5%BA%8F%E9%93%BE%E8%A1%A8"><span class="toc-number">2.5.</span> <span class="toc-text">合并两个有序链表</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BF%AB%E9%80%9F%E6%8E%92%E5%BA%8F"><span class="toc-number">2.6.</span> <span class="toc-text">快速排序</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%90%9C%E7%B4%A2%E7%AE%97%E6%B3%95"><span class="toc-number">3.</span> <span class="toc-text">搜索算法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%A1%BA%E5%BA%8F%E6%90%9C%E7%B4%A2"><span class="toc-number">3.1.</span> <span class="toc-text">顺序搜索</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BA%8C%E5%88%86%E6%90%9C%E7%B4%A2"><span class="toc-number">3.2.</span> <span class="toc-text">二分搜索</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="aside-list"><div class="aside-list-item no-cover"><a class="thumbnail" href="/post/a109015f.html" title="TS 中的类型验算,高级通用 API 实现"><img src="" data-lazy-src="https://ali-oss.xmwpro.com/posts/post_cover17.jpg" onerror='this.onerror=null,this.src="/img/404.jpg"' alt="TS 中的类型验算,高级通用 API 实现"></a><div class="content"><a class="title" href="/post/a109015f.html" title="TS 中的类型验算,高级通用 API 实现">TS 中的类型验算,高级通用 API 实现</a><time datetime="2023-06-26T15:26:24.000Z" title="发表于 2023-06-26 15:26:24">2023-06-26</time></div></div><div class="aside-list-item no-cover"><a class="thumbnail" href="/post/1ce87d42.html" title="使用 sort-imports 排序规则美化头部 import 代码"><img src="" data-lazy-src="https://ali-oss.xmwpro.com/posts/post_cover22.jpg" onerror='this.onerror=null,this.src="/img/404.jpg"' alt="使用 sort-imports 排序规则美化头部 import 代码"></a><div class="content"><a class="title" href="/post/1ce87d42.html" title="使用 sort-imports 排序规则美化头部 import 代码">使用 sort-imports 排序规则美化头部 import 代码</a><time datetime="2023-06-06T15:39:24.000Z" title="发表于 2023-06-06 15:39:24">2023-06-06</time></div></div><div class="aside-list-item no-cover"><a class="thumbnail" href="/post/b3e4ecaf.html" title="Vue 中如何监控用户网络状态"><img src="" data-lazy-src="https://ali-oss.xmwpro.com/posts/post_cover18.jpg" onerror='this.onerror=null,this.src="/img/404.jpg"' alt="Vue 中如何监控用户网络状态"></a><div class="content"><a class="title" href="/post/b3e4ecaf.html" title="Vue 中如何监控用户网络状态">Vue 中如何监控用户网络状态</a><time datetime="2023-05-22T16:08:02.000Z" title="发表于 2023-05-22 16:08:02">2023-05-22</time></div></div><div class="aside-list-item no-cover"><a class="thumbnail" href="/post/50b97751.html" title="在 vite 中使用 glob 实现约定式路由"><img src="" data-lazy-src="https://ali-oss.xmwpro.com/posts/post_cover43.jpg" onerror='this.onerror=null,this.src="/img/404.jpg"' alt="在 vite 中使用 glob 实现约定式路由"></a><div class="content"><a class="title" href="/post/50b97751.html" title="在 vite 中使用 glob 实现约定式路由">在 vite 中使用 glob 实现约定式路由</a><time datetime="2023-05-16T16:35:16.000Z" title="发表于 2023-05-16 16:35:16">2023-05-16</time></div></div><div class="aside-list-item no-cover"><a class="thumbnail" href="/post/7b74bd27.html" title="基于 React + Nest 的后台应用"><img src="" data-lazy-src="https://ali-oss.xmwpro.com/posts/post_cover45.jpg" onerror='this.onerror=null,this.src="/img/404.jpg"' alt="基于 React + Nest 的后台应用"></a><div class="content"><a class="title" href="/post/7b74bd27.html" title="基于 React + Nest 的后台应用">基于 React + Nest 的后台应用</a><time datetime="2023-04-18T10:39:21.000Z" title="发表于 2023-04-18 10:39:21">2023-04-18</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="site-business"><img src="" data-lazy-src="https://ali-oss.xmwpro.com/global/business.svg" alt="Cyan"></div><div class="site-services"><div class="site-services-link"><a class="site-services-link-item" href="https://www.aliyun.com/" rel="external nofollow noreferrer" target="_blank" title="阿里云提供cdn加速和云存储服务"><img src="" data-lazy-src="https://ali-oss.xmwpro.com/global/aliyun.svg" alt="阿里云"></a><a class="site-services-link-item" href="https://www.foreverblog.cn/blog/4240.html/" rel="external nofollow noreferrer" target="_blank" title="十年之约虫洞服务"><img src="" data-lazy-src="https://ali-oss.xmwpro.com/global/foreverblog-zh.svg" alt="十年之约"></a><a class="site-services-link-item" href="https://beian.miit.gov.cn/" rel="external nofollow noreferrer" target="_blank" title="粤ICP备2023007649号"><img src="" data-lazy-src="https://ali-oss.xmwpro.com/global/icp.png" alt="粤ICP备2023007649号"><span>粤ICP备2023007649号</span></a><a class="site-services-link-item" href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=44030402006264" rel="external nofollow noreferrer" target="_blank" title="粤公网安备44030402006264号"><img src="" data-lazy-src="https://ali-oss.xmwpro.com/global/security.png" alt="粤公网安备44030402006264号"><span>粤公网安备44030402006264号</span></a></div></div><div class="footer_custom_text"><p style="margin:0"><a target="_blank" rel="noopener external nofollow noreferrer" href="https://hexo.io/" style="margin-inline:5px"><img src="" data-lazy-src="https://ali-oss.xmwpro.com/global/hexo.svg" alt="博客框架 Hexo"></a><a target="_blank" rel="noopener external nofollow noreferrer" href="https://butterfly.js.org/" style="margin-inline:5px"><img src="" data-lazy-src="https://ali-oss.xmwpro.com/global/Butterfly.svg" alt="主题 Butterfly"></a><a target="_blank" rel="noopener external nofollow noreferrer" href="https://github.com/" style="margin-inline:5px"><img src="" data-lazy-src="https://ali-oss.xmwpro.com/global/github.svg" alt="本站托管于 Github"></a><a target="_blank" rel="noopener external nofollow noreferrer" href="https://creativecommons.org/licenses/by-nc-sa/4.0/" style="margin-inline:5px"><img src="" data-lazy-src="https://ali-oss.xmwpro.com/global/copyright.svg" alt="本站采用知识共享署名-非商业性使用-相同方式共享4.0国际许可协议进行许可"></a></p></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="to_comment" type="button" title="直达评论" onclick='cyan.scrollTo("#post-comment")'><i class="fas fa-comments"></i></button><button id="toggle-barrage" type="button" title="开启/关闭弹幕" onclick="cyan.switchCommentBarrage()"><i class="iconfont cyan-barrage"></i></button><button id="toggle-music" type="button" title="播放/暂停音乐" onclick="cyan.musicToggle()"><i class="fas fa-solid fa-music"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="nav-music"><div id="nav-music-hoverTips" onclick="cyan.musicToggle()">播放音乐</div><meting-js id="6589687940" server="netease" type="playlist" mutex="true" preload="none" theme="var(--cyan-theme-color)" data-lrctype="0" order="random"></meting-js></div><div id="algolia-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">全局搜索</span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="search-wrap"><div id="algolia-search-input"></div><div id="algolia-search-results"><div id="algolia-hits"></div><div id="algolia-pagination"></div><div id="algolia-info"><div class="algolia-stats"></div><div class="algolia-poweredBy"></div></div></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://ali-oss.xmwpro.com/cdn/js/fancybox.umd.js"></script><script src="https://ali-oss.xmwpro.com/cdn/js/instantclick-1.2.2.js" type="module"></script><script src="https://ali-oss.xmwpro.com/cdn/js/lazyload.iife.min.js"></script><script src="https://ali-oss.xmwpro.com/cdn/js/snackbar.min.js"></script><script src="https://ali-oss.xmwpro.com/cdn/js/algoliasearch-lite.umd.min.js"></script><script src="https://ali-oss.xmwpro.com/cdn/js/instantsearch.production.min.js"></script><script src="/js/search/algolia.js"></script><div class="js-pjax"><script>(()=>{const o=()=>{twikoo.init(Object.assign({el:"#twikoo-wrap",envId:"https://twikoo.xmwpro.com/",region:"",onCommentLoaded:function(){btf.loadLightbox(document.querySelectorAll("#twikoo .tk-content img:not(.tk-owo-emotion)"))}},null)),GLOBAL_CONFIG_SITE.isPost&&(()=>{const o=document.getElementById("twikoo-count");o&&twikoo.getCommentsCount({envId:"https://twikoo.xmwpro.com/",region:"",urls:[window.location.pathname],includeReply:!1}).then((function(t){o.innerText=t[0].count})).catch((function(o){console.error(o)}))})()},t=()=>{"object"!=typeof twikoo?getScript("https://ali-oss.xmwpro.com/cdn/js/twikoo.all.min.js").then(o):setTimeout(o,0)};t()})()</script></div><script>window.addEventListener("load",(()=>{const e=e=>{let t="";if(e.length)for(let n=0;n<e.length;n++){t+="<div class='aside-list-item'>";{const a="data-lazy-src";t+=`<a href='${e[n].url}' class='thumbnail'><img ${a}='${e[n].avatar}' alt='${e[n].nick}'></a>`}t+=`<div class='content'>\n        <a class='comment' href='${e[n].url}' title='${e[n].content}'>${e[n].content}</a>\n        <div class='name'><span>${e[n].nick} / </span><time datetime="${e[n].date}">${btf.diffDate(e[n].date,!0)}</time></div>\n        </div></div>`}else t+="没有评论";let n=document.querySelector("#card-newest-comments .aside-list");n.innerHTML=t,window.lazyLoadInstance&&window.lazyLoadInstance.update(),window.pjax&&window.pjax.refresh(n)},t=()=>{if(document.querySelector("#card-newest-comments .aside-list")){const t=saveToLocal.get("twikoo-newest-comments");t?e(JSON.parse(t)):(()=>{const t=()=>{twikoo.getRecentComments({envId:"https://twikoo.xmwpro.com/",region:"",pageSize:6,includeReply:!0}).then((function(t){const n=t.map((e=>{return{content:(t=e.comment,""===t||(t=(t=(t=(t=t.replace(/<img.*?src="(.*?)"?[^\>]+>/gi,"[图片]")).replace(/<a[^>]+?href=["']?([^"']+)["']?[^>]*>([^<]+)<\/a>/gi,"[链接]")).replace(/<pre><code>.*?<\/pre>/gi,"[代码]")).replace(/<[^>]+>/g,"")).length>150&&(t=t.substring(0,150)+"..."),t),avatar:e.avatar,nick:e.nick,url:e.url+"#"+e.id,date:new Date(e.created).toISOString()};var t}));saveToLocal.set("twikoo-newest-comments",JSON.stringify(n),10/1440),e(n)})).catch((function(e){document.querySelector("#card-newest-comments .aside-list").innerHTML="无法获取评论，请确认相关配置是否正确"}))};"object"==typeof twikoo?t():getScript("https://ali-oss.xmwpro.com/cdn/js/twikoo.all.min.js").then(t)})()}};t(),document.addEventListener("pjax:complete",t)}))</script><script async data-pjax src="/js/custom.js"></script><script async data-pjax src="/js/cascade.js"></script><script defer data-pjax src="//at.alicdn.com/t/c/font_3348168_pqjhlyxfz9r.js"></script><script async src="/js/commentBarrage.js"></script><script async data-pjax src="/js/sky.js"></script><script src="https://sdk.51.la/perf/js-sdk-perf.min.js" crossorigin="anonymous"></script><script>LA.init({id:"JxZKIeqz3SoTqaVu",ck:"JxZKIeqz3SoTqaVu"})</script><script>(new LingQue.Monitor).init({id:"JxZKIeqz3SoTqaVu",sendSuspicious:!0})</script><script src="/cyan/random.js"></script><script>let tianliGPT_postSelector="#post #article-container",tianliGPT_key="nWP7yQwRFXvk0piPhO2w"</script><script data-pjax src="https://ali-oss.xmwpro.com/cdn/js/tianli_gpt.js"></script><link rel="stylesheet" href="https://ali-oss.xmwpro.com/cdn/css/APlayer.min.css" media="print" onload='this.media="all"'><script src="https://ali-oss.xmwpro.com/cdn/js/APlayer.min.js"></script><script src="https://ali-oss.xmwpro.com/cdn/js/Meting.min.js"></script><script src="https://ali-oss.xmwpro.com/cdn/js/pjax.min.js"></script><script>let pjaxSelectors=["head > title","#config-diff","#body-wrap","#rightside-config-hide","#rightside-config-show",".js-pjax"];var pjax=new Pjax({elements:'a:not([target="_blank"]):not([href="/tags/"]):not([href="/categories/"]):not([href="/analysis/"]):not([href="/fcircle/"])',selectors:pjaxSelectors,cacheBust:!1,analytics:!0,scrollRestoration:!1});document.addEventListener("pjax:send",(function(){if(window.tocScrollFn&&window.removeEventListener("scroll",window.tocScrollFn),window.scrollCollect&&window.removeEventListener("scroll",scrollCollect),document.getElementById("rightside").style.cssText="opacity: ''; transform: ''",window.aplayers)for(let e=0;e<window.aplayers.length;e++)window.aplayers[e].options.fixed||window.aplayers[e].destroy();"object"==typeof typed&&typed.destroy();const e=document.body.classList;e.contains("read-mode")&&e.remove("read-mode"),"object"==typeof disqusjs&&disqusjs.destroy()})),document.addEventListener("pjax:complete",(function(){window.refreshFn(),document.querySelectorAll("script[data-pjax]").forEach((e=>{const t=document.createElement("script"),o=e.text||e.textContent||e.innerHTML||"";Array.from(e.attributes).forEach((e=>t.setAttribute(e.name,e.value))),t.appendChild(document.createTextNode(o)),e.parentNode.replaceChild(t,e)})),GLOBAL_CONFIG.islazyload&&window.lazyLoadInstance.update(),"function"==typeof chatBtnFn&&chatBtnFn(),"function"==typeof panguInit&&panguInit(),"function"==typeof gtag&&gtag("config","G-2P0LMHZNDD",{page_path:window.location.pathname}),"object"==typeof _hmt&&_hmt.push(["_trackPageview",window.location.pathname]),"function"==typeof loadMeting&&document.getElementsByClassName("aplayer").length&&loadMeting(),"object"==typeof Prism&&Prism.highlightAll()})),document.addEventListener("pjax:error",(e=>{404===e.request.status&&pjax.loadUrl("/404.html")}))</script></div><script>var fdata={apiurl:"https://friend-api.xmwpro.com/",initnumber:30,stepnumber:30,error_img:"https://npm.elemecdn.com/akilar-candyassets/image/404.gif"};localStorage.setItem("fdatalist",JSON.stringify(fdata))</script><script data-pjax src="https://ali-oss.xmwpro.com/cdn/js/fetch-friend.js"></script><script data-pjax src="https://ali-oss.xmwpro.com/cdn/js/random-friends-post.js"></script><script async src="//at.alicdn.com/t/c/font_3344355_6og082zqzfd.js"></script><div class="js-pjax"><script async>for(var arr=document.getElementsByClassName("recent-post-item"),i=0;i<arr.length;i++)arr[i].classList.add("wow"),arr[i].classList.add("animate__zoomIn"),arr[i].setAttribute("data-wow-duration",""),arr[i].setAttribute("data-wow-delay",""),arr[i].setAttribute("data-wow-offset","20"),arr[i].setAttribute("data-wow-iteration","")</script><script async>for(var arr=document.getElementsByClassName("bbTimeList"),i=0;i<arr.length;i++)arr[i].classList.add("wow"),arr[i].classList.add("animate__zoomIn"),arr[i].setAttribute("data-wow-duration",""),arr[i].setAttribute("data-wow-delay",""),arr[i].setAttribute("data-wow-offset","20"),arr[i].setAttribute("data-wow-iteration","")</script><script async>for(var arr=document.getElementsByClassName("card-widget"),i=0;i<arr.length;i++)arr[i].classList.add("wow"),arr[i].classList.add("animate__zoomIn"),arr[i].setAttribute("data-wow-duration",""),arr[i].setAttribute("data-wow-delay",""),arr[i].setAttribute("data-wow-offset","20"),arr[i].setAttribute("data-wow-iteration","")</script><script async>for(var arr=document.getElementsByClassName("category-in-bar"),i=0;i<arr.length;i++)arr[i].classList.add("wow"),arr[i].classList.add("animate__zoomIn"),arr[i].setAttribute("data-wow-duration",""),arr[i].setAttribute("data-wow-delay",""),arr[i].setAttribute("data-wow-offset","20"),arr[i].setAttribute("data-wow-iteration","")</script><script async>for(var arr=document.getElementsByClassName("bber-item"),i=0;i<arr.length;i++)arr[i].classList.add("wow"),arr[i].classList.add("animate__fadeInUp"),arr[i].setAttribute("data-wow-duration","1.5s"),arr[i].setAttribute("data-wow-delay",""),arr[i].setAttribute("data-wow-offset","20"),arr[i].setAttribute("data-wow-iteration","")</script><script async>for(var arr=document.getElementsByClassName("statistics-item"),i=0;i<arr.length;i++)arr[i].classList.add("wow"),arr[i].classList.add("animate__zoomIn"),arr[i].setAttribute("data-wow-duration","1.5s"),arr[i].setAttribute("data-wow-delay",""),arr[i].setAttribute("data-wow-offset","20"),arr[i].setAttribute("data-wow-iteration","")</script></div><script defer src="https://ali-oss.xmwpro.com/cdn/js/wow.min.js"></script><script defer src="https://ali-oss.xmwpro.com/cdn/js/wow_init.js"></script><script data-pjax src="https://ali-oss.xmwpro.com/cdn/js/gitcalendar.js"></script><script data-pjax>function gitcalendar_injector_config(){document.getElementById("recent-posts").insertAdjacentHTML("afterbegin",'<div class="recent-post-item" id="gitcalendarBar" style="width:100%;height:auto;padding:10px;"><style>#git_container{min-height: 280px}@media screen and (max-width:650px) {#git_container{min-height: 0px}}</style><div id="git_loading" style="width:10%;height:100%;margin:0 auto;display: block;"><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 50 50" style="enable-background:new 0 0 50 50" xml:space="preserve"><path fill="#d0d0d0" d="M25.251,6.461c-10.318,0-18.683,8.365-18.683,18.683h4.068c0-8.071,6.543-14.615,14.615-14.615V6.461z" transform="rotate(275.098 25 25)"><animatetransform attributeType="xml" attributeName="transform" type="rotate" from="0 25 25" to="360 25 25" dur="0.6s" repeatCount="indefinite"></animatetransform></path></svg><style>#git_container{display: none;}</style></div><div id="git_container"></div></div>'),console.log("已挂载gitcalendar")}document.getElementById("recent-posts")&&"/"===location.pathname&&(gitcalendar_injector_config(),GitCalendarInit("https://github-calendar.xmwpro.com/api?Cyan-Xmw",["#e3f2fd","#bbdefb","#90caf9","#64b5f6","#42a5f5","#2196f3","#1e88e5","#1976d2","#1565c0","#0d47a1","#425AEF"],"Cyan-Xmw"))</script></body></html>